package com.platform.usercenter.service.impl;

import java.util.*;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.platform.common.core.domain.entity.SysRole;
import com.platform.common.core.domain.entity.SysUser;
import com.platform.common.core.utils.DateUtils;
import com.platform.constants.SysUserConstants;
import com.platform.usercenter.domain.SysMenu;
import com.platform.usercenter.domain.dto.SysRoleBindVO;
import com.platform.usercenter.domain.query.SysRoleQuery;
import com.platform.usercenter.service.ISysUserCommonService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.platform.common.core.constant.UserConstants;
import com.platform.common.core.exception.ServiceException;
import com.platform.common.core.utils.SpringUtils;
import com.platform.common.core.utils.StringUtils;
import com.platform.common.datascope.annotation.DataScope;
import com.platform.common.security.utils.SecurityUtils;
import com.platform.usercenter.domain.SysRoleDept;
import com.platform.usercenter.domain.SysRoleMenu;
import com.platform.usercenter.domain.SysUserRole;
import com.platform.usercenter.mapper.SysRoleDeptMapper;
import com.platform.usercenter.mapper.SysRoleMapper;
import com.platform.usercenter.mapper.SysRoleMenuMapper;
import com.platform.usercenter.mapper.SysUserRoleMapper;
import com.platform.usercenter.service.ISysRoleService;

import javax.annotation.Resource;

/**
 * 角色 业务层处理
 *
 * @author
 */
@Service
public class SysRoleServiceImpl implements ISysRoleService
{
    @Resource
    private SysRoleMapper roleMapper;

    @Resource
    private SysRoleMenuMapper roleMenuMapper;

    @Resource
    private SysUserRoleMapper userRoleMapper;

    @Resource
    private SysRoleDeptMapper roleDeptMapper;
    @Resource
    private ISysUserCommonService commonService;

    /**
     * 根据条件分页查询角色数据
     *
     * @param roleQuery 角色信息
     * @return 角色数据集合信息
     */
    @Override
    public List<SysRole> selectRoleList(SysRoleQuery roleQuery)
    {
        return roleMapper.selectRoleList(roleQuery);
    }

    @Override
    public List<SysMenu> selectAppIdByRole(SysRoleQuery roleQuery) {
        return roleMapper.selectAppIdByRole(roleQuery);
    }

    @Override
    public List<com.platform.usercenter.domain.vo.SysRoleVO> getUserList(com.platform.usercenter.domain.vo.SysRoleVO roleQuery) {
        Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        if(!commonService.isAdmin(userId)){
            roleQuery.setOrgId(SecurityUtils.getLoginUser().getOrgId());
        }
        return roleMapper.getUserList(roleQuery);
    }

    @Override
    public List<com.platform.usercenter.domain.vo.SysRoleVO> getUsersByRoleIds(com.platform.usercenter.domain.vo.SysRoleVO roleQuery) {
        return roleMapper.getUserList(roleQuery);
    }

    @Override
    public List<com.platform.usercenter.domain.vo.SysRoleVO> getRoleUserList(com.platform.usercenter.domain.vo.SysRoleVO roleQuery) {
        Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        if(!commonService.isAdmin(userId)){
            roleQuery.setOrgId(SecurityUtils.getLoginUser().getOrgId());
        }
        return roleMapper.getRoleUserList(roleQuery);

    }

    @Override
    public List<SysRole> selectRoleListQuery(SysRoleQuery roleQuery)
    {
        if(!commonService.isAdmin(SecurityUtils.getLoginUser().getSysUser().getUserId())){
            roleQuery.setOrgId(SecurityUtils.getLoginUser().getOrgId());
            roleQuery.setIsAdmin(SysUserConstants.N);
        }
        return roleMapper.selectRoleList(roleQuery);
    }


    /**
     * 根据登录用户拥有或者创建的角色
     * @return
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SysRole> selectRolesByUserIdOrCreated(SysRoleQuery roleQuery) {

        List<SysRole> userRoles = roleMapper.selectRolePermissionByUserId(SecurityUtils.getUserId());


        if(!SysUser.isAdmin(SecurityUtils.getUserId())){
            roleQuery.setUserId(SecurityUtils.getUserId());
        }
        List<SysRole> roles = roleMapper.selectRoleList(roleQuery);
        for (SysRole role : roles)
        {
            for (SysRole userRole : userRoles)
            {
                if (role.getRoleId().longValue() == userRole.getRoleId().longValue())
                {
                    role.setFlag(true);
                    break;
                }
            }
        }
        return roles;

    }

    /**
     * 根据用户ID查询角色
     *
     * @param userId 用户ID
     * @return 角色列表
     */
    @Override
    public List<SysRole> selectRolesByUserId(Long userId)
    {
        List<SysRole> userRoles = roleMapper.selectRolePermissionByUserId(userId);
        List<SysRole> roles = selectRoleAll();
        for (SysRole role : roles)
        {
            for (SysRole userRole : userRoles)
            {
                if (role.getRoleId().longValue() == userRole.getRoleId().longValue())
                {
                    role.setFlag(true);
                    break;
                }
            }
        }
        return roles;
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectRolePermissionByUserId(Long userId)
    {
        List<SysRole> perms = roleMapper.selectRolePermissionByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (SysRole perm : perms)
        {
            if (StringUtils.isNotNull(perm))
            {
                permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 查询所有角色
     *
     * @return 角色列表
     */
    @Override
    public List<SysRole> selectRoleAll()
    {
        return SpringUtils.getAopProxy(this).selectRoleList(new SysRoleQuery());
    }
    /**
     * 查询所有角色：组织/角色
     *
     * @return 角色列表
     */
    @Override
    public List<SysRole> selectRoleAllList()
    {
        return roleMapper.selectRoleAllList(new SysRoleQuery());
    }

    /**
     * 根据用户ID获取角色选择框列表
     *
     * @param userId 用户ID
     * @return 选中角色ID列表
     */
    @Override
    public List<Long> selectRoleListByUserId(Long userId)
    {
        return roleMapper.selectRoleListByUserId(userId);
    }

    /**
     * 通过角色ID查询角色
     *
     * @param roleId 角色ID
     * @return 角色对象信息
     */
    @Override
    public SysRole selectRoleById(Long roleId)
    {
        return roleMapper.selectRoleById(roleId);
    }

    /**
     * 校验角色名称是否唯一
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public boolean checkRoleNameUnique(SysRole role)
    {
        Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
        SysRole info = roleMapper.checkRoleNameUnique(role.getRoleName(),role.getOrgId());
        if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验角色组织是否唯一
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public boolean checkRoleOrgUnique(SysRole role)
    {
        Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
        SysRoleQuery roleQuery = new SysRoleQuery();
        roleQuery.setRoleId(roleId);
        roleQuery.setOrgId(role.getOrgId());
        roleQuery.setDelFlag(SysUserConstants.ROLE_NOT_DEL);
        List<SysRole> roleList = roleMapper.selectRoleList(roleQuery);
        if (CollectionUtil.isNotEmpty(roleList)&& roleList.get(0).getRoleId().longValue() != roleId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验角色权限是否唯一
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public boolean checkRoleKeyUnique(SysRole role)
    {
        Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
        SysRole info = roleMapper.checkRoleKeyUnique(role.getRoleKey(),role.getOrgId());
        if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验角色是否允许操作
     *
     * @param role 角色信息
     */
    @Override
    public void checkRoleAllowed(SysRole role)
    {
        if (StringUtils.isNotNull(role.getRoleId()) && role.isAdmin())
        {
            throw new ServiceException("不允许操作超级管理员角色");
        }
    }

    /**
     * 校验角色是否有数据权限
     *
     * @param roleId 角色id
     */
    @Override
    public void checkRoleDataScope(Long roleId)
    {
        if (!SysUser.isAdmin(SecurityUtils.getUserId()))
        {
            SysRoleQuery roleQuery = new SysRoleQuery();
            roleQuery.setRoleId(roleId);
            List<SysRole> roles = SpringUtils.getAopProxy(this).selectRoleList(roleQuery);
            if (StringUtils.isEmpty(roles))
            {
//                throw new ServiceException("没有权限访问角色数据！");
            }
        }
    }

    /**
     * 通过角色ID查询角色使用数量
     *
     * @param roleId 角色ID
     * @return 结果
     */
    @Override
    public int countUserRoleByRoleId(Long roleId)
    {
        return userRoleMapper.countUserRoleByRoleId(roleId);
    }

    /**
     * 新增保存角色信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertRole(SysRole role)
    {
        // 新增角色信息
        return roleMapper.insertRole(role);
//        return insertRoleMenu(role);
    }

    @Override
    public int bindUserRole(SysRoleBindVO dto) {
        int rows=0;
        if(ObjectUtil.isNotEmpty(dto.getUserIds())){
            List<SysUserRole> userRoleList = new ArrayList<>();
            for (Long userId : dto.getUserIds()){
                SysUserRole userRole = new SysUserRole();
                userRole.setRoleId(dto.getRoleId());
                userRole.setUserId(userId);
                userRole.setOrgId(dto.getOrgId());
                userRole.setCreateBy(SecurityUtils.getUsername());
                userRole.setCreateTime(DateUtils.getNowDate());
                userRoleList.add(userRole);
            }
            userRoleMapper.batchUserRoleOrg(userRoleList);
            rows++;
        }
        return rows;
    }

    @Override
    public int cancelUserRole(SysRoleBindVO dto) {
        return  userRoleMapper.deleteUserRoleInfos(dto.getRoleId(),dto.getUserIds());
    }

    /**
     * 修改保存角色信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateRole(SysRole role)
    {
        // 修改角色信息
        int rows=roleMapper.updateRole(role);
        if(ObjectUtil.isNotEmpty(role.getMenuIds())){
            // 删除角色与菜单关联
            roleMenuMapper.deleteRoleMenuByRoleId(role.getRoleId());
            return insertRoleMenu(role);
        }else {
            return rows;
        }

    }
    /**
     * 修改保存角色信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int editRoleMenu(SysRole role)
    {
        // 修改角色信息
        int rows=roleMapper.updateRole(role);
        // 删除角色与菜单关联
        roleMenuMapper.deleteRoleMenuByRoleId(role.getRoleId());
        if(ObjectUtil.isNotEmpty(role.getMenuIds())){
            return insertRoleMenu(role);
        }else {
            return rows;
        }

    }

    /**
     * 修改角色状态
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public int updateRoleStatus(SysRole role)
    {
        return roleMapper.updateRole(role);
    }

    /**
     * 修改数据权限信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int authDataScope(SysRole role)
    {
        // 修改角色信息
        // 删除角色与部门关联
//        roleDeptMapper.deleteRoleDeptByRoleId(role.getRoleId());
        // 新增角色和部门信息（数据权限）
        return roleMapper.updateRole(role);
    }

    /**
     * 新增角色菜单信息
     *
     * @param role 角色对象
     */
    public int insertRoleMenu(SysRole role)
    {
        int rows = 1;
        // 新增用户与角色管理
        List<SysRoleMenu> list = new ArrayList<>();
        for (Long menuId : role.getMenuIds())
        {
            SysRoleMenu rm = new SysRoleMenu();
            rm.setRoleId(role.getRoleId());
            rm.setMenuId(menuId);
            rm.setOrgId(role.getOrgId());
            list.add(rm);
        }
        if (list.size() > 0)
        {
            rows = roleMenuMapper.batchRoleMenu(list);
        }
        return rows;
    }

    /**
     * 新增角色部门信息(数据权限)
     *
     * @param role 角色对象
     */
    public int insertRoleDept(SysRole role)
    {
        int rows = 1;
        // 新增角色与部门（数据权限）管理
        List<SysRoleDept> list = new ArrayList<>();
        for (Long deptId : role.getDeptIds())
        {
            SysRoleDept rd = new SysRoleDept();
            rd.setRoleId(role.getRoleId());
            rd.setDeptId(deptId);
            list.add(rd);
        }
        if (list.size() > 0)
        {
            rows = roleDeptMapper.batchRoleDept(list);
        }
        return rows;
    }

    /**
     * 通过角色ID删除角色
     *
     * @param roleId 角色ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteRoleById(Long roleId)
    {
        // 删除角色与菜单关联
        roleMenuMapper.deleteRoleMenuByRoleId(roleId);
        // 删除角色与部门关联
//        roleDeptMapper.deleteRoleDeptByRoleId(roleId);
        return roleMapper.deleteRoleById(roleId);
    }

    /**
     * 批量删除角色信息
     *
     * @param roleIds 需要删除的角色ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteRoleByIds(Long[] roleIds)
    {
        for (Long roleId : roleIds)
        {
            checkRoleAllowed(new SysRole(roleId));
            checkRoleDataScope(roleId);
            SysRole role = selectRoleById(roleId);
            if (countUserRoleByRoleId(roleId) > 0)
            {
                throw new ServiceException(String.format("%1$s已分配,不能删除", role.getRoleName()));
            }
        }
        // 删除角色与菜单关联
        roleMenuMapper.deleteRoleMenu(roleIds);
        // 删除角色与部门关联
        return roleMapper.deleteRoleByIds(roleIds);
    }

    /**
     * 取消授权用户角色
     *
     * @param userRole 用户和角色关联信息
     * @return 结果
     */
    @Override
    public int deleteAuthUser(SysUserRole userRole)
    {
        return userRoleMapper.deleteUserRoleInfo(userRole);
    }

    /**
     * 批量取消授权用户角色
     *
     * @param roleId 角色ID
     * @param userIds 需要取消授权的用户数据ID
     * @return 结果
     */
    @Override
    public int deleteAuthUsers(Long roleId, Long[] userIds)
    {
        return userRoleMapper.deleteUserRoleInfos(roleId, userIds);
    }

    /**
     * 批量选择授权用户角色
     *
     * @param roleId 角色ID
     * @param userIds 需要授权的用户数据ID
     * @return 结果
     */
    @Override
    public int insertAuthUsers(Long roleId, Long[] userIds)
    {
        // 新增用户与角色管理
        List<SysUserRole> list = new ArrayList<>();
        for (Long userId : userIds)
        {
            SysUserRole ur = new SysUserRole();
            ur.setUserId(userId);
            ur.setRoleId(roleId);
            list.add(ur);
        }
        return userRoleMapper.batchUserRole(list);
    }

    @Override
    public Set<String> selectRolePermissionByUserIdAndDeptId(Long userId, Long orgId) {
        {
            List<SysRole> perms = roleMapper.selectRolePermissionByUserIdAndDeptId(userId,orgId);
            Set<String> permsSet = new HashSet<>();
            for (SysRole perm : perms)
            {
                if (StringUtils.isNotNull(perm))
                {
                    permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
                }
            }
            return permsSet;
        }
    }

}
